from django.shortcuts import render,redirect,HttpResponse
from app01.models import Department,UserInfo,PhoneNumber
from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError
from django.utils.safestring import mark_safe
from app01.utils.pagination import Pagination
from app01.utils.bootstrapmodel import BootStrapModelForm
def user_list(request):
    """用户列表"""

    queryset=UserInfo.objects.all()
    page_obj=Pagination(request,queryset)
    for i in page_obj.page_queryset:
        # print(i.name,i.salary,i.create_time.strftime("%Y-%m-%d"),i.gender)
        # print(i.gender) #1/2
        # print(i.get_gender_display())
        # print(i.depart_id)
        departname=Department.objects.filter(id=i.depart_id).first()
        # print(departname.title)
        # print(i.depart.title)
    context={'userinfo': page_obj.page_queryset,
             "page_string":page_obj.html()}
    return render(request,'user_list.html',context)
#==================ModelForm实例===========
from django import forms
# class UserModelForm(forms.ModelForm):
class UserModelForm(BootStrapModelForm):
    '''员工表'''
    name = forms.CharField(
        min_length=3,
        label="用户名"
        # ,widgets=forms.TextInput(attrs={'class':"form-control"}),
        )
    # password=form.CharField(label='密码' ,validaters=正则表达式)
    class Meta:
        model=UserInfo
        fields=['name','password','age','gender','address','salary','create_time','depart']
        # fields=['name','password','age','gender','address']
        # widgets={
        #     'name':forms.TextInput(attrs={'class':"form-control"}),
        #     'password':forms.TextInput(attrs={'class':"form-control"}),
        #     'age':forms.TextInput(attrs={'class':"form-control"}),
        #     'gender':forms.TextInput(attrs={'class':"form-control"}),
        #     'address':forms.TextInput(attrs={'class':"form-control"}),
        #     'salary':forms.TextInput(attrs={'class':"form-control"}),
        #     'create_time':forms.TextInput(attrs={'class':"form-control"}),
        #     'depart':forms.TextInput(attrs={'class':"form-control"}),
        # }
    # def __init__(self,*args,**kwargs):
    #     super().__init__(*args,**kwargs)
    #     #循环找到所有的插件添加属性
    #     for name,field in self.fields.items():
    #         # if name=='password':
    #         #     continue
    #         # print("=======================")
    #         # print(name,field)
    #         field.widget.attrs={'class':'form-control','placeholder':field.label}
def user_add(request):
    '''添加用户部门原始方法'''
    if request.method=='GET':
        context={
            'gender_choices':UserInfo.gender_choices,
            'depart_list':Department.objects.all()
        }
        print(context['gender_choices'])
        return render(request,'user_add.html',context)
    #Post 方法获取用户提供的数据
    name=request.POST.get('name')
    password=request.POST.get('pwd')
    age=request.POST.get('age')
    gender=request.POST.get('gender')
    address=request.POST.get('address')
    salary=request.POST.get('salary')
    create_time=request.POST.get('create_time')
    depart_id=request.POST.get('depart_name')
    UserInfo.objects.create(name=name,password=password,age=age,gender=gender,address=address,salary=salary,create_time=create_time,depart_id=depart_id)

    return redirect('/user/list')
def user_modelform_add(request):
    '''添加用户（ModelForm版本）'''
    if request.method=='GET':
        form=UserModelForm()
        # for i in form:
        #     print(i)
        return render(request,"user_modelform_add.html",{'form':form})
    #用户POST提交数据
    form =UserModelForm(data=request.POST)
    # print(form)
    if form.is_valid():#将数据逐一进行检查是否为空
        print(form.cleaned_data)
        # model.UserInfo.objects.create(..)
        form.save()
        return redirect('/user/list/')
    else:#校验失败
        print(form.errors)
        return render(request, "user_modelform_add.html", {'form': form})
def user_edit(request,nid):
    rowobj = UserInfo.objects.filter(id=nid).first()
    "用户更新"
    if request.method=='GET':
        #根据ID去数据库获取要编辑的那一行

        form =UserModelForm(instance=rowobj)

        return render(request,'user_edit.html',{'form':form})
    else:
        form=UserModelForm(data=request.POST,instance=rowobj)
        if form.is_valid():
            #默认保存的是用户输入的所有数据,如果想要用户在用户以外增加一点值
            #form.instance.字段名=值
            form.save()
            return redirect("/user/list/")
        else:#效验失败
            print(form.errors)
            return render(request,'/user/edit/',{'form':form})
def user_del(request,nid):
    UserInfo.objects.filter(id=nid).delete()
    return redirect('/user/list/')